String.prototype.format = function () {
    let formatted = this;
    for (var arg in arguments) {
        formatted = formatted.replace("{" + arg + "}", arguments[arg]);
    }
    return formatted;
};


// 异步Get请求:
async function get(path) {
    return await request('GET', path);
}

// 异步Post请求:
async function post(path, params) {
    return await request('POST', path, JSON.stringify(params));
}

// 异步请求:
async function request(method, path, data) {
    try {
        return await $.ajax({
            type: method,
            url: path,
            data: data,
            contentType: 'application/json',
            dataType: 'json'
        });
    } catch (err) {
        if (err.responseJSON) {
            throw err.responseJSON;
        }
        throw err;
    }
}

// jQuery
$(document).ready(function () {
    console.log('页面加载完成！');

    initApp()
});


function initApp() {
    var vm = new Vue({
        el: '#app',
        data: {
            picList: [],
            nextUrl: "pic/page?pageNo={0}&pageSize={1}",
            pageNo: 1,
            pageSize: 500
        },
        watch: {
            /* $route(to, from) {
                 const scrollEl = document.querySelector('#app');
                 scrollEl.addEventListener("scroll", this.handleScroll);
             }*/
        },
        methods: {
            async loadNextPage() {
                let resp = await get(this.nextUrl.format(this.pageNo, this.pageSize));
                this.picList = [...this.picList, ...resp.data];
                this.pageNo = this.pageNo + 1;
                this.load();
            },
            handleScroll() {
                console.log("enter ......")
                // 判断是否滚动到底部
                if (window.innerHeight + window.pageYOffset >= document.body.offsetHeight) {
                    // 加载下一页数据
                    this.loadNextPage().then(r =>
                        console.error()
                    );
                }
            },
            load() {
                // 级联网格布局库 实现瀑布流
                let $grid = $('.wall').masonry({
                    columnWidth: '.wall-item',  // 列宽度
                    itemSelector: '.wall-item',  // 选择的元素
                    fitWidth: true,  // 固定宽度
                    horizontalOrder: true,  // 从左往右
                    gutter: 10  // 左右间距
                });
                // 在每个图像加载完成后触发
                $(".illust").imagesLoaded().progress(function (instance, image) {
                    let $img = $(image.img);
                    let $loading = $img.parent("a").siblings("div.is-loading");
                    // 移除加载动画
                    $loading.hide();
                    // 显示加载完成后的图片
                    $img.removeClass("illust-loading");
                    // 重新加载 masonry
                    $grid.masonry('layout');
                });
                // 图片灯箱
                $('.container').on('click', function () {
                    $.fancybox.open($("[data-fancybox]"), {
                        // Custom options
                        buttons: [
                            "zoom",
                            //"share",
                            "slideShow",
                            //"fullScreen",
                            "download",
                            "thumbs",
                            "close"
                        ],
                    }, $(this).index());
                    return false;
                });
            }
        },
        mounted: async function () {
            let resp = [];
            try {
                let url = this.nextUrl;
                resp = await get(url.format(this.pageNo, this.pageSize));
                this.picList = resp.data
            } catch (err) {
                console.error('load bars failed: ' + err);
            }
            /* const scrollEl = document.querySelector('#app');
             scrollEl.addEventListener("scroll", this.handleScroll);*/
        },
        updated: function () {
            this.load();
        },
        destroyed: function () {
            /*  const scrollEl = document.querySelector('#app');
              scrollEl.removeEventListener("scroll", this.handleScroll);*/
        }
    });
}


